import wx
from wx.lib import iewin
import urllib
import json
from kursk_daemon import *

class MyFrame(wx.Frame):

    def __init__(self):
        """Init IEHtmlWindow and set ourselves as event sink"""
        wx.Frame.__init__(self, None, title="IEHtmlWindow", size=(650, 700))
        self.ie = iewin.IEHtmlWindow(self)
        self.ie.AddEventSink(self)
        self.ie.Navigate("https://api.weibo.com/oauth2/authorize?client_id=298661557&response_type=code&redirect_uri=https://api.weibo.com/oauth2/default.html")
        self.Centre()
        
    def DocumentComplete(self, this, pDisp, URL):
        hlink = self.ie.ctrl.Document.location.href
        #element3 = element.QueryInterface(MSHTML.IHTMLElement3)
        #element3.contentEditable = "true"
        if(hlink.find('https://api.weibo.com/oauth2/default.html') == 0):
            i = hlink.index('code=')
            code = hlink[i+5:]
            token = self.queryToken(code)
            self._token = token
            #dlg = wx.MessageDialog(None, token, u"mytitle", wx.OK | wx.ICON_QUESTION)
            #dlg.ShowModal()
            #dlg.Destroy()
            self._daemon = KurskDaemon(token)
            self._daemon.start()
            
    def queryToken(self, code):
        tokenUrlTpl = 'https://api.weibo.com/oauth2/access_token?grant_type=authorization_code&redirect_uri=https://api.weibo.com/oauth2/default.html&code=%s'
        params = {}
        params['client_id'] = '298661557'
        params['client_secret'] = '6e665c273599822027ad5f71804f9e13'
        
        tokenUrl = tokenUrlTpl % (code)
        print(tokenUrl)
        
        params = urllib.urlencode(params)
        fout = urllib.urlopen(tokenUrl, params).readline()
        print('tokenJson:%s\n'%(fout))
        
        jsonObj = json.loads(fout)
        return jsonObj['access_token']
        
app = wx.App(False)
MyFrame().Show()
app.MainLoop()